﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZHDJ.Core.Util;
using ZHDJ.Data.BLL;
using ZHDJ.Data.Models.Edu;
using ZHDJ.Data.Models.Questionnaire;
using ZHDJ.WebPage;

namespace ZHDJ.Web.Portal.Questionnaire
{
    public partial class Default : PortalPage
    {
        #region  属性

        /// <summary>
        /// 字母数组
        /// </summary>
        public string[] _leter = new string[] {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M"};


        /// <summary>
        /// 问卷ID
        /// </summary>
        public string QuestionnaireID
        {
            get { return this.Request["id"] ?? "null"; }

        }

        /// <summary>
        /// 题目选项（做题前）
        /// </summary>
        private DataSet _TestSubject;

        /// <summary>
        /// 题目选项（做题前）
        /// </summary>
        public DataSet TestSubject
        {
            get
            {
                if (_TestSubject == null)
                {
                    _TestSubject = PartyQuestionnaire.GetPartyQuestionnaireSubjectTest(QuestionnaireID);
                    _TestSubject.Tables[1].Columns.Add("CategoryName", typeof (string));
                    _TestSubject.Tables[1].Columns.Add("SID", typeof (string));

                }
                return _TestSubject;
            }
        }


        public PartyQuestionnaire q { get; set; }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(QuestionnaireID))
            {
                RegisterJs("loadError()");
            }

            q = DB.PartyQuestionnaires.Find(QuestionnaireID);
            if (q == null || string.IsNullOrEmpty(q.Title))
            {
                RegisterJs("loadError()");
            }
            if (q.Stauts != 4)
            {
                RegisterJs("StautsError()");
            }
            if (q.BeginTime.Value>DateTime.Now)
            {
                RegisterJs("nobegin()");
            }
            if (q.EndTime.Value < DateTime.Now)
            {
                RegisterJs("end()");
            }
            CheckLogin(true);
            if (
               DB.PartyQuestionnaireRecords.Count(
                   a => a.QuestionnaireID == QuestionnaireID && a.CreateBy == CurrentUser.LoginID) > 0)
            {

                RegisterJs("joinIn()");
                return;
            }
            if (q.TestObject == "1" && CurrentUser.runSate != "0")
            {
                RegisterJs("nop()");
                return;
            }
            if (q.TestObject == "2" && CurrentUser.runSate != "-1")
            {
                RegisterJs("nop()");
                return;
            }
            if (!IsPostBack)
            {
                hdQuestionnaireID.Value = QuestionnaireID;
                lblTitle.Text = q.Title;
                LoadData();
            }
        }

        public void RegisterJs(string js, string key = "tip")
        {
            divbtnsubmit.Visible = false;
            ClientScript.RegisterStartupScript(this.GetType(), key, string.Format(";{0};", js), true);
        }

        #region 数据加载

        public void LoadData()
        {
            //加载题目
            var dv = TestSubject.Tables[0].AsDataView();
            dv.Sort = "OrderNo";

            this.rptSubject.DataSource = dv;
            this.rptSubject.DataBind();

            foreach (DataRowView item in dv)
            {
                this.hdSubjectIDs.Value += Convert.ToString(item["ID"]) + ",";
            }
        }

        #endregion


        #region 事件

        /// <summary>
        /// 绑定选项
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void rptSubject_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem ||
                e.Item.ItemType == ListItemType.SelectedItem)
            {
                //加载选项
                var data = e.Item.DataItem;
                Repeater Repeater = e.Item.FindControl("rptOptions") as Repeater;
                HiddenField hiddenField = e.Item.FindControl("hdSubjectID") as HiddenField;
                HiddenField CategoryName = e.Item.FindControl("hdCategoryName") as HiddenField;
                if (Repeater == null)
                {
                    return;
                }
                if (IsPostBack)
                {
                    
                }
                else
                {
                    //答题前
                    var dt = TestSubject.Tables[1];
                    var formNames = new List<string>();
                    var index = 0;
                    foreach (DataRow dr in dt.Rows)
                    {
                        if (dr["SubjectID"].ToString() != hiddenField.Value)
                        {
                            continue;
                        }
                        dr["CategoryName"] = CategoryName.Value;
                        dr["SID"] = dr["ID"];
                        if (CategoryName.Value == "radio")
                        {
                            dr["ID"] = hiddenField.Value;
                        }
                        if (!formNames.Contains(hiddenField.Value + "_" + CategoryName.Value))
                        {
                            formNames.Add(dr["ID"]+ "_"+CategoryName.Value);
                        }
                        if (dr["IsTk"].ToString().ToLower() == "1" || dr["IsTk"].ToString().ToLower() == "true")
                        {
                            formNames.Add(dr["ID"] + "_" + dr["SID"] + "_name");
                        }
                        index += 1;
                    }
                    this.hdFormName.Value += "," + string.Join(",", formNames.ToArray());
                    var dataview = TestSubject.Tables[1].AsDataView();

                    dataview.RowFilter = string.Format("SubjectID='{0}'", hiddenField.Value);
                    Repeater.DataSource = dataview;
                    Repeater.DataBind();
                    //divRs.Visible = false;
                }

            }
        }

        public string GetOpVisbile(object isTk)
        {
            if (isTk != DBNull.Value && (isTk.ToString().ToLower() == "1" || isTk.ToString().ToLower() == "true"))
            {
                return "1";
            }
            return "0";
        }

        /// <summary>
        /// 提交测试
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSubmitEx_Click(object sender, EventArgs e)
        {
            if (
                DB.PartyQuestionnaireRecords.Count(
                    a => a.QuestionnaireID == QuestionnaireID && a.CreateBy == CurrentUser.LoginID) > 0)
            {
                //防止重复提交
                RegisterJs("chongfuError()");
                return;
            }
            var formnames =
                hdFormName.Value.Split(',').ToList().Where(a => !string.IsNullOrEmpty(a)).OrderBy(a => a.Length);
            List<TestSubject> test = new List<TestSubject>();
            var oTable = (from o in DB.PartyQuestionnaireOptions
                join s in DB.PartyQuestionnaireSubjects on o.SubjectID equals s.ID
                where s.QuestionnaireID == QuestionnaireID
                select o).ToList();

            foreach (var item in formnames)
            {
                var value = Request.Form[item];
                if (string.IsNullOrEmpty(value))
                {
                    continue;
                }
                var opid = "";
                if (item.Contains("_checkbox"))
                {
                    opid = item.Split('_')[0];
                }
                else if (item.Contains("_radio"))
                {
                    opid = value;
                }
                else if (item.Contains("_name"))
                {
                    opid = item.Split('_')[1];
                }

                TestSubject subject = new TestSubject();
                subject.SubjectID = oTable.First(a => a.ID == opid).SubjectID;

               
                if (item.Contains("_name"))
                {
                    foreach (var t in test)
                    {
                        if(t.Submit.Any() && t.Submit[0].Keys.Contains(opid))
                            t.Submit[0][opid] = value;
                    }
                }
                else
                {
                    subject.Submit.Add(new Dictionary<string, string> {{value, ""}});
                }
                test.Add(subject);
            }
            SaveData(test);
        }



        /// <summary>
        /// 保存数据
        /// </summary>
        /// <param name="test"></param>
        private void SaveData(List<TestSubject> test)
        {
            PartyQuestionnaireRecord re = new PartyQuestionnaireRecord();
            re.ID = StringHelper.NewID;
            re.CreateBy = CurrentUser.LoginID;
            re.CreateTime = DateTime.Now;
            re.QuestionnaireID = QuestionnaireID;
            re.UserName = CurrentUser.UserName;


            //添加提交记录
            DB.PartyQuestionnaireRecords.Add(re);

            List<PartyQuestionnaireRecordDetail> details = new List<PartyQuestionnaireRecordDetail>();

            foreach (var subject in test)
            {
                foreach (var option in subject.Submit)
                {
                    PartyQuestionnaireRecordDetail detail = new PartyQuestionnaireRecordDetail();
                    detail.ID = StringHelper.NewID;

                    detail.SubjectID = subject.SubjectID;
                    detail.RecordID = re.ID;
                    detail.OptionID = option.First().Key;
                    detail.Tk = "";
                    if (!string.IsNullOrEmpty(option.First().Value))
                    {
                        detail.Tk = option.First().Value;
                    }
                    details.Add(detail);
                }
            }
            DB.PartyQuestionnaireRecordDetails.AddRange(details);
            DB.SaveChanges();
            PartyQuestionnaire.QuestionnaireStatistics(QuestionnaireID);
            RegisterJs("su();");
        }


        #endregion


    }


    /// <summary>
    /// 处理测试实体
    /// </summary>
    public class TestSubject
    {
        public TestSubject()
        {
            Answer = new List<string>();
            Submit = new List<Dictionary<string, string>>();
        }

        /// <summary>
        /// 题目ID
        /// </summary>
        public string SubjectID { get; set; }
        /// <summary>
        /// 题目答案选项ID
        /// </summary>
        public List<string> Answer { get; set; }

        /// <summary>
        /// 用户提交的答案选项ID
        /// </summary>
        public List<Dictionary<string,string>> Submit { get; set; }

        /// <summary>
        /// 是否做对
        /// </summary>
        public bool IsRight { get; set; }

    }
}